package com.example.demo.filter;

import com.example.demo.myUtils.CommonPrefix;
import com.example.demo.myUtils.WebUtils;
import com.example.demo.pojo.ResultCode;
import com.example.demo.pojo.ResultPojo;
import com.example.demo.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: 防重放过滤器
 * @Auther:ccc
 * @Date:2023/2/25 14:21
 */
@WebFilter
public class AntiReplayFilter implements Filter {

    @Value("${AntiReplay.enabled}")
    private Boolean flag;

    @Autowired
    private RedisService redisService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (flag) {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            String reqId = request.getHeader("reqId");
            //log.info("------放重放获取上送id:{}", reqId);
            if (StringUtils.isEmpty(reqId)) {
                WebUtils.writeJson(response, new ResultPojo(ResultCode.REPLAY_IDFAULT));
                return;
            }
            String seq = CommonPrefix.REQ_PREFIX + reqId;
            if (redisService.hasKey(seq)) {
                WebUtils.writeJson(response, new ResultPojo(ResultCode.REPLAY_NOT));
                return;
            } else {
                redisService.set(seq, seq, 30L);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }


}
